package com.geek.typehandler;



import com.geek.util.JacksonUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * implements TypeHandler 或 extends BaseTypeHandler
 * String[] -> String
 * String -> String[]
 * Typehandler类上增加两个注解：对应类型 javaType、jdbcType
 */
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayTypeHandler implements TypeHandler<String[]> {
    // 预编译的SQL语句提供参数的过程

    /**
     * @param ps PreparedStatement对象
     * @param index ？占位符序号
     * @param parameter 提供的值
     * @throws SQLException
     */
    @Override
    public void setParameter(PreparedStatement ps, int index, String[] parameter, JdbcType jdbcType) throws SQLException {
        // String[] → String
        String str = JacksonUtil.write(parameter);
        ps.setString(index,str);
    }

    // String → String[]
    // 从结果集中获取值，转换成set方法能够接受的参数类型
    @Override
    public String[] getResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        if (str == null || "".equals(str)) {
            return new String[0];
        }
        String[] array = JacksonUtil.read(str, String[].class);
        return array;
    }

    @Override
    public String[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        String[] array = JacksonUtil.read(str, String[].class);
        return array;
    }

    @Override
    public String[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String str = cs.getString(columnIndex);
        String[] array = JacksonUtil.read(str, String[].class);
        return array;
    }
}
